from collections import defaultdict

from mongolog.models import CASLog
from strategy.models import Strategy

APPS_DANGER_TYPE_MAP = {
    'prv': '隐私窃取',
    'rmt': '远程控制',
    'pay': '恶意扣费',
    'spr': '恶意传播',
    'exp': '资费消耗',
    'sys': '系统破坏',
    'fra': '诱骗欺诈',
    'rog': '流氓行为',
    'ads': '广告插件',
}


def translate_apps_danger_type(danger_type):
    try:
        return APPS_DANGER_TYPE_MAP[danger_type]
    except KeyError:
        return '其他类型'


def translate_apps_sensitive_type(sensitive_type):
    return sensitive_type


def get_device_uuid_strategy():
    """# 通过cas表，strategy表，构建 "device_uuid" 关联 strategy.name 表。
    """
    device_strategy = defaultdict(list)
    strategy_aqueryset = Strategy.objects.all()
    uid_name_dict = {}
    for strategy_aqueryset_i in strategy_aqueryset:
        uid_name_dict[strategy_aqueryset_i.uid] = strategy_aqueryset_i.name
    # 查询cas的数据表，获取设备登录信息，提取该设备触发的策略，安全状态
    cas_queryset = CASLog.objects.mongo_aggregate([
        {
            '$match': {
                'device_uuid': {
                    '$exists': True,
                    '$ne': ''},
                # 'platform': platform
            }
        },
        {
            '$project': {
                '_id': 0,
                'device_uuid': 1,
                'strategy': 1,
                # 'platform': 1
            }
        }
    ])
    for queryset_i in cas_queryset:
        try:
            device_strategy[queryset_i['device_uuid']].append(uid_name_dict[queryset_i['strategy']])
        except:
            pass

    return device_strategy


